<script lang="ts">
	import { page } from '$app/state';
	import {
		THREAD_STATE,
		type ThreadContentInfo,
		type ThreadInfo
	} from '$lib/api/proto/roadmap_qa_api';
	import { USER_ROLE } from '$lib/api/proto/user_api';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { Undo2, UserRound } from 'lucide-svelte';
	import moment from 'moment';
	import EditorJS from '@editorjs/editorjs';

	const PAGE_SIZE = 10;

	const roadmapId = page.url.searchParams.get('roadmapId') ?? '';
	const threadId = page.url.searchParams.get('threadId') ?? '';

	let threadInfo = $state(null as ThreadInfo | null);
	let contentList = $state([] as ThreadContentInfo[]);
	let totalCount = $state(0);
	let curPage = $state(0);

	const pageCount = $derived(Math.ceil(totalCount / PAGE_SIZE));

	let contentEditor: EditorJS | null = $state(null);

	async function loadThreadInfo() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapQaApiClient.getThread({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				threadId: threadId
			}).response
		);
		threadInfo = res.thread ?? null;
	}

	async function loadContentList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.roadmapQaApiClient.listContent({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				threadId: threadId,
				offset: PAGE_SIZE * curPage,
				limit: PAGE_SIZE
			}).response
		);
		contentList = res.contentList;
		totalCount = res.totalCount;
	}

	async function setThreadState(newState: THREAD_STATE) {
		if (userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.roadmapQaApiClient.updateThreadState({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				threadId: threadId,
				threadState: newState
			}).response
		);
		await loadThreadInfo();
	}

	async function addContent() {
		if (userStore.userSession == null || contentEditor == null) {
			return;
		}
		const contentData = await contentEditor.save();
		if (contentData.blocks.length == 0) {
			appStore.addToastMessage({
				level: 'warning',
				content: '内容为空',
				keepTime: 2000
			});
			return;
		}
		await callApi(
			appStore.roadmapQaApiClient.addContent({
				sessionId: userStore.userSession,
				roadmapId: roadmapId,
				threadId: threadId,
				content: JSON.stringify(contentData)
			}).response
		);

		contentEditor.clear();

		const newPageCount = Math.ceil((totalCount + 1) / PAGE_SIZE);
		if (curPage != newPageCount - 1) {
			curPage = newPageCount - 1;
		} else {
			await loadContentList();
		}
	}

	$effect(() => {
		loadThreadInfo();
	});

	$effect(() => {
		loadContentList();
	});
</script>

<div class="absolute right-[20px] flex gap-2 items-center">
	<button class="btn btn-accent" onclick={() => history.back()}>
		<Undo2 size={16} />返回
	</button>
</div>

<div class="h-[calc(100vh-110px)] overflow-y-auto w-full pl-[100px] pr-[100px]">
	<div class="prose max-w-none relative bg-base-300 h-[56px] rounded-box p-2">
		<h2>{threadInfo?.basicInfo?.name}</h2>
		<div class="absolute right-[20px] top-[4px]">
			{#if userStore.userInfo?.userId == threadInfo?.askUserId && userStore.userInfo?.basicInfo?.userRole == USER_ROLE.USER_ROLE_STUDENT}
				<div role="tablist" class="tabs tabs-box">
					<button
						role="tab"
						class="tab {threadInfo?.threadState == THREAD_STATE.THREAD_STATE_OPEN
							? 'tab-active'
							: ''}"
						onclick={() => setThreadState(THREAD_STATE.THREAD_STATE_OPEN)}>打开回复</button
					>
					<button
						role="tab"
						class="tab {threadInfo?.threadState == THREAD_STATE.THREAD_STATE_CLOSE
							? 'tab-active'
							: ''}"
						onclick={() => setThreadState(THREAD_STATE.THREAD_STATE_CLOSE)}>关闭回复</button
					>
				</div>
			{:else if threadInfo?.threadState == THREAD_STATE.THREAD_STATE_OPEN}
				<div class="badge badge-info text-xl h-[40px]">可回复</div>
			{:else if threadInfo?.threadState == THREAD_STATE.THREAD_STATE_CLOSE}
				<div class="badge badge-info text-xl h-[40px]">回复已关闭</div>
			{/if}
		</div>
	</div>
	<div class="mt-[40px]">
		{#each contentList as content}
			<div class="flex gap-2 bg-base-200 p-2 rounded-box">
				{#if content.optUserLogoUri == ''}
					<UserRound size={24} />
				{:else}
					<div class="avatar">
						<div class="w-[24px] rounded-full">
							<img alt="avatar" src={content.optUserLogoUri} />
						</div>
					</div>
				{/if}
				{content.optUserDisplayName}
				{moment(Number(content.optTime)).format('YYYY-MM-DD HH:mm:ss')}
			</div>
			<SimpleEditor
				readOnly
				data={content.content}
				sizeClass="border-2 border-base-200 rounded-box mb-[20px]"
			/>
		{/each}
	</div>

	{#if pageCount > 1}
		<div class="join bg-base-200 absolute right-0 mr-[100px] mt-[20px]">
			{#if curPage > 0}
				<button class="join-item btn btn-lg" onclick={() => (curPage = curPage - 1)}>上一页</button>
			{/if}
			{#if curPage != 0}
				<button
					class="join-item btn btn-lg {curPage == 0 ? 'btn-active' : ''}"
					onclick={() => (curPage = 0)}>1</button
				>
			{/if}
			{#if pageCount > 3 && curPage > 1}
				<button class="join-item btn btn-lg btn-disabled">...</button>
			{/if}
			{#if curPage < pageCount}
				<button class="join-item btn btn-lg btn-active">{curPage + 1}</button>
			{/if}
			{#if curPage + 1 < pageCount}
				<button class="join-item btn btn-lg" onclick={() => (curPage += 1)}>{curPage + 2}</button>
			{/if}
			{#if pageCount - curPage > 4}
				<button class="join-item btn btn-lg btn-disabled">...</button>
			{/if}
			{#if pageCount - curPage > 3}
				<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 2)}
					>{pageCount - 1}</button
				>
			{/if}
			{#if pageCount - curPage > 2}
				<button class="join-item btn btn-lg" onclick={() => (curPage = pageCount - 1)}
					>{pageCount}</button
				>
			{/if}
			{#if curPage + 1 < pageCount}
				<button class="join-item btn btn-lg" onclick={() => (curPage = curPage + 1)}>下一页</button>
			{/if}
		</div>
	{/if}

	{#if threadInfo?.threadState == THREAD_STATE.THREAD_STATE_OPEN && curPage == pageCount - 1}
		<div class="prose max-w-none {pageCount > 1 ? 'mt-[50px]' : 'mt-[20px]'}">
			<h3>{userStore.userInfo?.userId == threadInfo.askUserId ? '继续提问' : '回复提问'}</h3>
			<SimpleEditor
				sizeClass="border-2 border-base-200 min-h-[300px]"
				placeholder="请输入......"
				onInit={(tmpEditor) => (contentEditor = tmpEditor)}
			/>
			<div class="flex justify-end mt-[20px]">
				<button class="btn btn-primary btn-xl" onclick={() => addContent()}
					>{userStore.userInfo?.userId == threadInfo.askUserId ? '提问' : '回复'}</button
				>
			</div>
		</div>
	{/if}
</div>
